package mg.daloji.antandroyd.ui;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;


import mg.daloji.antandroyd.CONSTANTS;
import mg.daloji.antandroyd.R;
import mg.daloji.antandroyd.Radio;
import mg.daloji.antandroyd.application.App;
import mg.daloji.antandroyd.service.IServiceRadio;
import mg.daloji.antandroyd.service.IServiceRadioCallBack;
import mg.daloji.antandroyd.service.ServiceRadio;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class Home extends Activity{

	private static final int TEXT_UPDATE = 0;
	private static String PACKAGE ="com.speakingcode.example.android.MediaPlayerService";
	private ImageButton btnPlay;
	private ImageButton btnNext;
	private ImageButton btnPrevious;
	private ImageView image;
	private SeekBar songProgressBar;
	private TextView songTitleLabel;
	private TextView songCurrentDurationLabel;
	private TextView songTotalDurationLabel;
	// Media Player
	private  MediaPlayer mMediaPlayer;
	
	private ServiceRadio service;
	// Handler to update UI timer, progress bar etc,.
	private Handler mHandler = new Handler();;

	private Context mContext;

	private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
	
	
	private IServiceRadioCallBack mObserver;
	private ServiceConnection mConnection;
	private Radio radio_select;
	private boolean mBound =false; 
	private boolean isplaying =false;
	private ProgressDialog mWaitDialog;
	private IServiceRadio mService;
	private int current_radio=0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.player);
		Bundle extras = getIntent().getExtras(); 
		if (extras != null) {
			current_radio = extras.getInt(CONSTANTS.INDEX);
		}
		mContext=getApplicationContext();
		mWaitDialog = new ProgressDialog(this);
		songTitleLabel=(TextView) findViewById(R.id.songTitle);
		btnPlay = (ImageButton) findViewById(R.id.btnPlay);
		btnNext = (ImageButton) findViewById(R.id.btnNext);
		btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
		image =(ImageView) findViewById(R.id.image);
		
		btnPlay.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// check for already playing
				if(mBound){
					try{
						if(!isplaying){
							playRadio();
						}else{
							isplaying=false;
					    	btnPlay.setImageResource(R.drawable.btn_play);
					    	mService.doStop(mObserver);
						}
					}catch (RemoteException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
		
		
		btnNext.setOnClickListener(new View.OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
		       try {
		    	   current_radio++;
				   if(current_radio>App.getConf().size()-1){
						current_radio=0;
					}
			       radio_select =App.getConf().get(current_radio);
			       songTitleLabel.setText(radio_select.getNom()); 
			       setImage(radio_select.getTrigramme());
			       showWaitDialog();
			       mService.doStop(mObserver);
				   mService.doStart(mObserver, radio_select);
		       } catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			}
			
		});
		
		btnPrevious.setOnClickListener(new View.OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try {
			    	   current_radio--;
			    	   if(current_radio<0){
			    		  current_radio=App.getConf().size() -1;
			    	   }
				       radio_select =App.getConf().get(current_radio);
				       songTitleLabel.setText(radio_select.getNom()); 
				       setImage(radio_select.getTrigramme());
				       mService.doStop(mObserver);
					   mService.doStart(mObserver, radio_select);
			       } catch (RemoteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		});
		mHandler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what){
				case TEXT_UPDATE:
					songTitleLabel.setText((CharSequence) msg.obj);
				}
			}
		};
		
		 mObserver = new IServiceRadioCallBack.Stub() {

			@Override
			public void streamingReady() throws RemoteException {
				// TODO Auto-generated method stub
				hideWaitDialog();
			}

			@Override
			public void errorStreaming() throws RemoteException {
				// TODO Auto-generated method stub
				hideWaitDialog();
				Toast.makeText(mContext, "Erreur de synchronisation "
	    			      + Thread.currentThread().getName(), Toast.LENGTH_LONG).show();
			}
			
		
		};
		
		mConnection = new ServiceConnection(){	
    		public void onServiceDisconnected(ComponentName name) {
    			mService = null;
    
    		}


			@Override
			public void onServiceConnected(ComponentName arg0, IBinder service) {
				// TODO Auto-generated method stub
				mService = IServiceRadio.Stub.asInterface(service);
    			try{
    				mService.setObserver(mObserver);
    			}catch(RemoteException e){
    			}
    			mBound = true;
    			playRadio();
			}
    	};
		
    	bindService();
	}

  private void playRadio(){
	  radio_select=App.getConf().get(current_radio);
	  if(radio_select!=null){
		  try {
			    isplaying=true;
				radio_select=App.getConf().get(current_radio);
				songTitleLabel.setText(radio_select.getNom());
				setImage(radio_select.getTrigramme());
				 image.setImageBitmap(radio_select.getImage());
			    //image.setImageResource(R.drawable.antsiva);
				btnPlay.setImageResource(R.drawable.btn_pause);
			    showWaitDialog();
			    mService.doStart(mObserver, radio_select);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	  }
  }
	
	
  private void setImage(String name){
	  
	  if(name.equalsIgnoreCase(CONSTANTS.ANTSIVA)){
		 image.setBackgroundResource(R.drawable.antsiva); 
	  }
	  if(name.equalsIgnoreCase(CONSTANTS.RDJ)){
			 image.setBackgroundResource(R.drawable.rdj); 
		  }
	  if(name.equalsIgnoreCase(CONSTANTS.VIVA)){
			 image.setBackgroundResource(R.drawable.viva); 
		  }
	  if(name.equalsIgnoreCase(CONSTANTS.RNM)){
			 image.setBackgroundResource(R.drawable.rdj); 
		  }
	  
	  
  }
  
	/**
	 * Dismisses the wait dialog if any
	 */
	private void hideWaitDialog() {
		if (null != this.mWaitDialog) {
			this.mWaitDialog.dismiss();
		}
	}
	
	private void showWaitDialog() {
		// just in case:
		hideWaitDialog();
		try {
			mWaitDialog = ProgressDialog.show(this,radio_select.getNom(),"Synchronisation",true,true,new OnCancelListener() {
				public void onCancel(final DialogInterface dialog) {
					finish();
				}
			});
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.mWaitDialog.setOwnerActivity(this);
	}
	
	private void bindService(){
		Intent intent = new Intent(getApplicationContext(), ServiceRadio.class);
		bindService(intent, mConnection, BIND_AUTO_CREATE);
	}


	/**
	 * Receiving song index from playlist view
	 * and play the song
	 * */
	@Override
	protected void onActivityResult(int requestCode,
			int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}


	@Override
	public void onDestroy(){
		super.onDestroy();
	}

}